/**
 * @file ext-barry.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */

const name = 'barry'

const loadExtensionTranslation = async function (svgEditor) {
    let translationModule
    const lang = svgEditor.configObj.pref('lang')
    try {
        translationModule = await import(`./locale/${lang}.js`)
    } catch (_error) {
        console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
        translationModule = await import('./locale/en.js')
    }
    svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
    name,
    async init() {
        const svgEditor = this
        const { svgCanvas } = svgEditor
        const { ChangeElementCommand } = svgCanvas.history
        const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
        const { $id, $click, $qq, $ } = svgCanvas
        let lastBBox = {}
        let started
        let newFO, newuse
        let p = {
            x: 0, y: 0, h: 3, w: 3, headx: 0, heady: 0
        }
        await loadExtensionTranslation(svgEditor)

        const createLg = (id) => {
            var tmp = `<svg><defs><linearGradient id="lg_barry_${id}" x1="0" x2="0" y1="0.805" y2="0.8">
        <stop offset="0" stop-color="#7fff00"/>
        <stop offset="1" stop-opacity="0"/>
       </linearGradient></defs></svg>`
            var lgs = $(tmp).find("defs>*")
            svgCanvas.findDefs().append(lgs[0]);
        }

        const createSymbol = (id) => {
            var symbol = `<svg><defs><symbol id="symbol_barry_${id}" preserveAspectRatio="xMidYMid meet" viewBox="0 0 80 100">
        <text fill="none" font-family="Serif" font-size="24" id="${id}_texthd" opacity="1" stroke="#000000" stroke-width="0" text-anchor="middle" transform="matrix(0.857143 0 0 0.818182 2.85714 0)" x="40.83" xml:space="preserve" y="0"></text>
        <rect class="barry" fill="url(#lg_barry_${id})" height="82.64" id="${id}_barry" rx="6" ry="6" stroke="#000" stroke-width="2" width="55.71" x="10" y="8.18"/>
        <rect class="barry_head" fill="#000" height="6.36" id="${id}_head" rx="2" ry="2" stroke="#000" width="18.57" x="28.57" y="1.83"/>
        <text fill="#FF0000" font-family="Serif" font-size="24" id="${id}_text" opacity="1" stroke="#000000" stroke-width="0" text-anchor="middle" transform="matrix(0.857143 0 0 0.818182 2.85714 0)" x="40.83" xml:space="preserve" y="60.5">20%</text>
       </symbol></defs></svg>`
            var lgs = $(symbol).find("defs>*")
            svgCanvas.findDefs().append(lgs[0]);
            return `symbol_barry_${id}`
        }

        return {
            name: svgEditor.i18next.t(`${name}:name`),
            // The callback should be used to load the DOM with the appropriate UI items
            callback() {
                // Add the button and its handler(s)
                // Note: the star extension needs to be loaded before the polygon extension
                const fbtitle = `${name}:title`
                const titleStar = `${name}:buttons.0.title`
                const titlePolygon = `${name}:buttons.1.title`
                const buttonTemplate = `
                <se-button id="tool_barry" title="${titlePolygon}" src="barry.svg">
                </se-button>
            `
                svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 8)

                $click($id('tool_barry'), () => {
                    if (this.leftPanel.updateLeftPanel('tool_barry')) {
                        svgCanvas.setMode('barry')
                    }
                })
            },
            mouseDown(opts) {
                if (svgCanvas.getMode() === 'barry') {
                    started = true
                    //'x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'
                    p.x = opts.start_x
                    p.y = opts.start_y
                    var svgId = svgCanvas.getNextId()
                    createLg(svgId)
                    newFO = svgCanvas.addSVGElementsFromJson({
                        element: 'g',
                        attr: {
                            class: 'ems',
                            'doc-type': 'barry',
                            id: svgId
                        }
                    })
                    var symbolId = createSymbol(svgId)
                    newuse = svgCanvas.addSVGElementsFromJson({
                        element: 'use',
                        attr: {
                            class: 'use',
                            "xlink:href": `#${symbolId}`,
                            x: p.x, y: p.y, width: 80, height: 100
                        }
                    });
                    newFO.append(newuse)
                    lastBBox = newFO.getBBox()
                    return {
                        started: true
                    }
                }
                return undefined
            },
            mouseMove(opts) {
                if (!started) {
                    return undefined
                }
                const zoom = svgCanvas.getZoom()
                let x = opts.mouse_x / zoom
                let y = opts.mouse_y / zoom;
                if (svgCanvas.getMode() === 'barry') {
                    if (svgCanvas.getCurConfig().gridSnapping) {
                        x = svgCanvas.snapToGrid(x)
                        y = svgCanvas.snapToGrid(y)
                    }
                    const tlist = newFO.transform.baseVal
                    const box = newFO.getBBox()
                    const left = box.x; const top = box.y

                    const newbox = {
                        width: Math.abs(x - p.x),
                        height: Math.abs(y - p.y)
                    }

                    let sx = (newbox.width / lastBBox.width) || 1
                    let sy = (newbox.height / lastBBox.height) || 1

                    // Not perfect, but mostly works...
                    let tx = 0
                    if (x < p.x) {
                        tx = lastBBox.width
                    }
                    let ty = 0
                    if (y < p.y) {
                        ty = lastBBox.height
                    }

                    // update the transform list with translate,scale,translate
                    const translateOrigin = svgroot.createSVGTransform()
                    const scale = svgroot.createSVGTransform()
                    const translateBack = svgroot.createSVGTransform()

                    translateOrigin.setTranslate(-(left + tx), -(top + ty))


                    scale.setScale(sx, sy)

                    translateBack.setTranslate(left + tx, top + ty)
                    tlist.appendItem(translateBack)
                    tlist.appendItem(scale)
                    tlist.appendItem(translateOrigin)

                    svgCanvas.recalculateDimensions(newFO)
                    svgCanvas.selectorManager.requestSelector(newFO).resize()
                    svgCanvas.call('transition', newFO)

                    lastBBox = newFO.getBBox()

                    return {
                        started: true
                    }
                }
                return undefined
            },
            mouseUp() {
                if (svgCanvas.getMode() === 'barry') {
                    const keep = true;
                    return {
                        keep,
                        element: newFO
                    }
                }
                return undefined
            },
            updateBarry(val) {

                if (val.mode == "barry") {
                    const elem = svgCanvas.getSelectedElements()
                    var id = $(elem).attr('id');
                    var defs = svgCanvas.findDefs();
                    var barry_border_color = val.data.barry_border_color;
                    var barry_color = val.data.barry_color;
                    $(elem).attr("data", `${val.data.tableValue}:${val.data.equipmentLable}:${val.data.domainID}`)
                    if ($("#symbol_barry_" + id)[0] == undefined) {
                        createLg(id)
                        createSymbol(id)
                        $(elem).find("use").attr("xlink:href", '#symbol_barry_' + id)
                    }
                    $(defs).find('#symbol_barry_' + id).find('rect').eq(0).attr('stroke', barry_border_color)
                    $(defs).find('#symbol_barry_' + id).find('rect').eq(1).attr('stroke', barry_border_color)
                    $(defs).find('#symbol_barry_' + id).find('rect').eq(1).attr('fill', barry_border_color)
                    $(defs).find('#lg_barry_' + id).find('stop').eq(0).attr('stop-color', barry_color)

                    if (val.data.showValue) {
                        var opts = val.data.valueFont;
                        setText(1, opts)
                    } else if (!val.data.showValue) {
                        $(defs).find('#symbol_barry_' + id).find('text').eq(1).attr('fill', 'none')
                    }

                    if (val.data.showtitle) {
                        var opts = val.data.fontSetValue;
                        setText(0, opts)
                    } else if (!val.data.showtitle) {
                        $(defs).find('#symbol_barry_' + id).find('text').eq(0).attr('fill', 'none')
                    }
                    function setText(index, opts) {
                        if (index == 0) {
                            var color = val.data.title_color;
                            var title = val.data.title;

                            $(defs).find('#symbol_barry_' + id).attr("viewBox", '0 -30 80 130')
                            $(defs).find('#symbol_barry_' + id).find('text').eq(index).text(title)
                        } else {
                            var color = val.data.value_color;
                        }
                        $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('fill', color)

                        //字体样式设置
                        if (opts.typeVal.indexOf("bold") > -1) {
                            $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('font-weight', 'bold')
                        } else {
                            $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('font-weight', 'normal')
                        }
                        if (opts.typeVal.indexOf("italic") > -1) {
                            $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('font-style', 'italic')
                        } else {
                            $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('font-style', 'none')
                        }

                        if (opts.typeVal.indexOf("underline") > -1 || opts.typeVal.indexOf("line-through") > -1) {
                            if (opts.typeVal.indexOf("underline") > -1 && opts.typeVal.indexOf("line-through") > -1) {
                                $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('text-decoration', 'underline line-through')
                            } else {
                                if (opts.typeVal.indexOf("underline") > -1) {
                                    $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('text-decoration', 'underline')
                                }

                                if (opts.typeVal.indexOf("line-through") > -1) {
                                    $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('text-decoration', 'line-through')
                                }

                            }
                        } else {
                            $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('text-decoration', ' ')
                        }

                        if (opts.fontfirst) {
                            $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('font-family', opts.fontfirst)

                        }
                        if (opts.fontnumber) {
                            $(defs).find('#symbol_barry_' + id).find('text').eq(index).attr('font-size', opts.fontnumber)
                        }
                    }

                    $(elem).attr("state", btoa(unescape(encodeURIComponent(JSON.stringify(val)))))
                    svgEditor.layersPanel.populateObjects()
                    // addToHistory(new ChangeElementCommand(elem, { state: btoa(unescape(encodeURIComponent(JSON.stringify(val)))) }))
                }

            }
        }
    }
}
